#!/bin/bash

set -e

cat > openssl.conf <<EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localstorage-webhook
DNS.2 = localstorage-webhook.kube-system
DNS.3 = localstorage-webhook.kube-system.svc
DNS.4 = localstorage-webhook.kube-system.svc.{{ coredns.domain }}
EOF


openssl genrsa -out tls.key 2048

openssl req -new -key tls.key -out tls.csr \
    -subj "/CN=localstorage/C=CN/ST=ZheJiang/L=HangZhou/O=localstorage" \
    -config openssl.conf

openssl x509 -req -in tls.csr \
    -CA /etc/kubernetes/{{ cluster_name }}/pki/ca.crt -CAkey /etc/kubernetes/{{ cluster_name }}/pki/ca.key \
    -CAcreateserial -out tls.crt \
    -days 36500 -extensions v3_req \
    -extfile openssl.conf

openssl x509 -in tls.crt -noout -text

kubectl --kubeconfig /etc/kubernetes/{{ cluster_name }}/admin.conf -n kube-system get secret localstorage-webhook-secret || \
    kubectl --kubeconfig /etc/kubernetes/{{ cluster_name }}/admin.conf -n kube-system \
    create secret generic localstorage-webhook-secret \
    --from-file=tls.key --from-file=tls.crt --from-file=/etc/kubernetes/{{ cluster_name }}/pki/ca.crt
